package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增商品，保存spu所有信息
     * TODO 高级部分再完善（如存在问题，事务无法解决多服务之间的问题）
     * @GlobalTransactional
     * @param vo
     */

    @Transactional
    @Override
    public void saveSupInfo(SupSaveVo vo) {
        Class<SpuInfoEntity> spuInfoEntityClass = this.currentModelClass();

        //1、保存spu基本信息 `pms_spu_info`
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2、保存spu的描述信息（图片） `pms_spu_info_desc`
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3、保存spu的图片集 `pms_spu_images`
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        //4、保存spu的规格参数 `pms_product_attr_value`
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((item) -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setSpuId(spuInfoEntity.getId());
            valueEntity.setAttrId(item.getAttrId());
            //属性名需要再查一遍
            AttrEntity entity = attrService.getById(item.getAttrId());
            valueEntity.setAttrName(entity.getAttrName());
            valueEntity.setAttrValue(item.getAttrValues());
            valueEntity.setQuickShow(item.getShowDesc());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrs(collect);

        //5、保存spu的积分信息 gulimall_sms库->`sms_spu_bounds`
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }

        //6、保存当前spu对应的所有sku信息
        //6.1)、sku的基本信息 `pms_sku_info`
        //6.2)、sku的图片信息 `pms_sku_images`
        //6.3)、sku的销售属性信息 `pms_sku_sale_attr_value`
        //6.4)、sku的满件打折、满多少减多少、会员价格
        //      gulimall_sms库->`sms_sku_ladder`->`sms_sku_full_reduction`->`sms_member_price`

        List<Skus> skus = vo.getSkus();
        if (skus!=null && skus.size()>0){
            skus.forEach(item->{
                String skuDefaultImg="";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg()==1){
                        skuDefaultImg=image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                //默认图片
                skuInfoEntity.setSkuDefaultImg(skuDefaultImg);
                //6.1)、sku的基本信息 `pms_sku_info`
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuId);
                    imagesEntity.setImgUrl(img.getImgUrl());
                    imagesEntity.setDefaultImg(img.getDefaultImg());
                    return imagesEntity;
                }).filter(entity->{
                    //过滤（图片url为空的，无需保存）。返回true就是需要，false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //6.2)、sku的图片信息 `pms_sku_images`
                skuImagesService.saveBatch(imagesEntities);

                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(a -> {
                    SkuSaleAttrValueEntity valueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, valueEntity);
                    valueEntity.setSkuId(skuId);
                    return valueEntity;
                }).collect(Collectors.toList());
                //6.3)、sku的销售属性信息 `pms_sku_sale_attr_value`
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //6.4)、sku的满件打折、满多少减多少、会员价格
                //      gulimall_sms库->`sms_sku_ladder`->`sms_sku_full_reduction`->`sms_member_price`
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){

                }
                R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                if (r1.getCode()!=0){
                    log.error("远程保存sku优惠信息失败");
                }

            });
        }
    }

    /**
     * 保存spu基本信息
     * @param spuInfoEntity
     */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * spu检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Transactional
    @Override
    public void up(Long spuId) {
        //1.查出当前spuid对应的所有sku信息，品牌名字
        List<SkuInfoEntity> skus=skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id",spuId));
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //查询sku的所有可以被检索的规格属性(注意：不用每个sku都查一遍，所有拎到sku循坏外面）
        //1.)查出spu对应的所有属性id值，attrIds
        List<ProductAttrValueEntity> entities = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = entities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.)过滤attrIds集合中，检索值不为1的属性id，searchAttrIds
        List<Long> searchAttrIds=attrService.selectSearchAttrIds(attrIds);
        //3.)根据searchAttrIds来查出spu对应的所有可以被检索的规格属性
        Set<Long> isSet=new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> collect1 = entities.stream().filter(item -> {
            return isSet.contains(item.getAttrId());
        }).map(item2 -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item2, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //TODO 远程调用库存服务查商品是否有库存
        //(注意：不用每个sku都远程调用一次，所有拎到sku循坏外面）
        Map<Long, Boolean> stockMap=null;

        try{
            R r = wareFeignService.getSkusHasStock(skuIds);
            //
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常：原因{}",e);
        }

        Map<Long, Boolean> finalStockMap = stockMap;
        //2.封装每个sku的信息为SkuEsModel
        List<SkuEsModel> collect = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel1 = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel1);
            //skuPrice、skuImg
            esModel1.setSkuPrice(sku.getPrice());
            esModel1.setSkuImg(sku.getSkuDefaultImg());

            // hasStock、hotScore
            //TODOo 远程调用库存服务查商品是否有库存
            if (finalStockMap ==null){
                esModel1.setHasStock(true);
            }else{
                esModel1.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            //TODO hotScore热度评分。0
            esModel1.setHotScore(0L);

            //brandName、brandImg、catalogName
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel1.setBrandName(brandEntity.getName());
            esModel1.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(esModel1.getCatalogId());
            esModel1.setCatalogName(categoryEntity.getName());

            //List<Attrs> attrs
            //查询sku的所有可以被检索的规格属性
            //1.)查出spu对应的所有属性id值，attrIds
            //4.)录入数据
            esModel1.setAttrs(collect1);

            return esModel1;
        }).collect(Collectors.toList());


        //TODO 3.将数据发送给es进行保存：gulimall-search服务来处理
        R r = searchFeignService.productStatusUp(collect);
        if (r.getCode()==0){
            //远程调用成功
            //TODOO 修改当前商品的上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //远程调用失败
            //TODO 存在问题：重复调用？接口幂等性；重试机制？
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }
}